<?php
//   +----------------------------------------------------------------------
//   | Copyright (c) 2015-2025 http://www.hdphp.cn All rights reserved.
//   | Licensed ( http://www.hdphp.cn/licenses/ )
//   | Author: Jack <sophia2152@qq.com>
//   | 官方网址: http://www.hdphp.cn
//   | 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
//   | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
//   +----------------------------------------------------------------------
namespace hdphp\listener\system\http;

use think\facade\Log;
use think\Request;
use think\Response;

/**
 * Class：HTTP请求结束回调事件
 * 创建人：Jack
 * 创建时间：2024/1/12 15:51
 * @package app\listener\system\http
 */
class HttpEnd
{
    public function handle(Response $response): void
    {
        try {
            // 业务成功和失败分开存储
            $errcode = isset($response->getData()["errcode"]) ? $response->getData()["errcode"] : 0;
            if ($errcode == 200) {
                // 业务成功日志开关
                if (!config("log.success_log")) return;
                $logType = "success";
            } else {
                // 业务失败日志开关
                if (!config("log.fail_log")) return;
                $logType = "fail";
            }
            $request = app()->make(Request::class);
            // 当前用户身份标识
            if ($request->hasMacro('uid')) {
                $uid = $request->uid();
                $type = 'user';
            } else if ($request->hasMacro('adminId')) {
                $uid = $request->adminId();
                $type = 'admin';
            } else if ($request->hasMacro('kefuId')) {
                $uid = $request->kefuId();
                $type = 'kefu';
            } else if ($request->hasMacro('outId')) {
                $uid = $request->outId();
                $type = 'out';
            } else if ($request->hasMacro('storeId')) {
                $uid = $request->storeId();
                $type = 'store';
            } else if ($request->hasMacro('cashierId')) {
                $uid = $request->cashierId();
                $type = 'cashier';
            } else if ($request->hasMacro('supplierId')) {
                $uid = $request->supplierId();
                $type = 'supplier';
            } else {
                $uid = 0;
                $type = '';
            }
            // 日志内容
            $log = [
                $uid,                                                                                      // 用户ID
                $type,                                                                                     // 类型
                $request->ip(),                                                                            // 客户ip
                ceil(msectime() - (request()->time(true) * 1000)),                                    // 耗时（毫秒）
                str_replace("/", "", $request->rootUrl()),                                   // 应用
                $request->baseUrl(),                                                                       // 路由
                json_encode($request->param(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),     // 请求参数
                json_encode($response->getData(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),  // 响应数据
            ];
            Log::write(implode("|", $log), $logType);
        } catch (\Throwable $e) {
            $data = [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTrace(),
                'previous' => $e->getPrevious(),
            ];
            Log::error(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        }
    }
}